package com.parktech.sun.web.controller.management.sunhz;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.sunhz.Enterprise;
import com.parktech.sun.domain.model.sunhz.EnterpriseCategoryProduct;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.sunhz.EnterpriseService;
import com.parktech.sun.utils.FileHelper;
import com.parktech.sun.utils.ImageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * User: Think
 * Date: 2010-12-28
 * Time: 2:52:45
 */
@Controller
@RequestMapping("/management/enterprises")
public class EnterpriseController {

    private int pageSize = Constants.PAGINATION_PAGE_SIZE;

    private EnterpriseService enterpriseService;

    @Autowired
    public EnterpriseController(EnterpriseService enterpriseService) {
        this.enterpriseService = enterpriseService;
    }

    @RequestMapping(value = "/search", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView search(@ModelAttribute EnterpriseSearchForm enterpriseSearchForm) {

        Page page = new Page(pageSize, enterpriseSearchForm.getPageNo());

        ModelAndView modelAndView = new ModelAndView("management/sunhz/enterpriseSearch");

        return modelAndView.addObject(
                enterpriseService.search(
                        enterpriseSearchForm.getName(), enterpriseSearchForm.getCategory(), enterpriseSearchForm.getPublishStatus(), page));
    }

    @RequestMapping(value = "/search", method = RequestMethod.DELETE)
    public String delete(@RequestParam("enterpriseIds") Long[] enterpriseIds) {
        enterpriseService.deleteAll(enterpriseIds);
        return "redirect:search";
    }

    @ModelAttribute("random")
    public String random() {
        return Math.random() + "";
    }

    @ModelAttribute("allCategoryProducts")
    public Map<Long, List<EnterpriseCategoryProduct>> populateAllCategoryProducts() {

        Map<Long, List<EnterpriseCategoryProduct>> allCategoryProducts = new HashMap<Long, List<EnterpriseCategoryProduct>>();

        Map<Long, String> allCategories = populateAllCategories();
        Set<Long> categoryKeys = allCategories.keySet();

        for (Long category : categoryKeys) {
            allCategoryProducts.put(category, enterpriseService.listProductByCategory(category));
        }
        return allCategoryProducts;
    }
    @ModelAttribute("allCategories")
    public Map<Long, String> populateAllCategories() {
        Map<Long, String> allCategories = new TreeMap<Long, String>();
        allCategories.put(1L, "硅料与硅片");
        allCategories.put(2L, "电池片与组件");
        allCategories.put(4L, "薄膜电池");
        allCategories.put(8L, "辅料与设备");
        allCategories.put(16L, "系统集成");
        allCategories.put(32L, "服务机构");
        return allCategories;
    }

    @ModelAttribute("allIsMemberOptions")
    public Map<Boolean, String> populateAllIsMemberOptions() {
        Map<Boolean, String> allRecommendOptions = new TreeMap<Boolean, String>();
        allRecommendOptions.put(true, "是");
        allRecommendOptions.put(false, "否");
        return allRecommendOptions;
    }

    @ModelAttribute("allRecommendOptions")
    public Map<Boolean, String> populateAllRecommendOptions() {
        Map<Boolean, String> allRecommendOptions = new TreeMap<Boolean, String>();
        allRecommendOptions.put(true, "是");
        allRecommendOptions.put(false, "否");
        return allRecommendOptions;
    }

    @ModelAttribute("allPublishStatus")
    public Map<Integer, String> populateAllPublishStatus() {
        Map<Integer, String> allPublishStatus = new HashMap<Integer, String>();
//        allPublishStatus.put(-1, "所有");
        allPublishStatus.put(0, "未发布");
        allPublishStatus.put(1, "已发布");
        return allPublishStatus;
    }

    @RequestMapping(value = "/{enterpriseId}", method = RequestMethod.GET)
    public String edit(@PathVariable Long enterpriseId, Model model) {
        Enterprise enterprise = enterpriseService.getById(enterpriseId);
        model.addAttribute(enterprise);
        return "management/sunhz/enterpriseForm";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute(new Enterprise());
        return "management/sunhz/enterpriseForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String save(@ModelAttribute @Valid Enterprise enterprise,
                       BindingResult result,
                       @RequestParam("productListIds") Long[] productIds,
                       @RequestParam("logoFile") MultipartFile logoFile,
                       HttpServletRequest request) throws IOException {

        if (result.hasErrors()) {
            return "management/sunhz/enterpriseForm";
        }
        enterpriseService.clearThenSaveOrUpdateBean(enterprise);

//        List<EnterpriseCategoryProduct> existProductList = enterprise.getProductList();

        List<EnterpriseCategoryProduct> productList = new ArrayList<EnterpriseCategoryProduct>();
        for (Long productId : productIds) {
            if (productId == -1) continue;
            productList.add(new EnterpriseCategoryProduct(productId));
        }
        enterprise.setProductList(productList);
        if (logoFile != null && !logoFile.isEmpty()) {
            processLogo(enterprise, logoFile, request.getSession().getServletContext());
        }
        enterpriseService.saveOrUpdateBean(enterprise);

        return "redirect:/management/enterprises/search";
    }

    private void processLogo(Enterprise enterprise, MultipartFile logo, ServletContext servletContext) throws IOException {

        String enterprisePath = servletContext.getRealPath("/upload/enterprise/" + enterprise.getId());
        File enterpriseDir = new File(enterprisePath);
        if (!enterpriseDir.exists()) enterpriseDir.mkdirs();

        File logoFile = new File(enterpriseDir, "logo.jpg");
        if (logoFile.exists()) {
            logoFile.delete();
        }
//        ImageHelper.resizeFix(logo.getInputStream(), logoFile, 200, 110);
        FileHelper.saveFile(logo.getInputStream(), logoFile);
        enterprise.setHaveLogo(true);
    }


}
